package com.cc.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密
 * 单向加密算法
 * 特点：加密速度快，不需要秘钥，但是安全性不高，需要搭配随机盐值使用
 *
 */
public class MD5Util {

	public static String sign(String content, String salt, String charset) {
		content = content + salt;
		return DigestUtils.md5Hex(getContentBytes(content, charset));
	}

	public static boolean verify(String content, String sign, String salt, String charset) {
		content = content + salt;
		String mysign = DigestUtils.md5Hex(getContentBytes(content, charset));
		return mysign.equals(sign);
	}

	private static byte[] getContentBytes(String content, String charset) {
		if (!"".equals(charset)) {
			try {
				return content.getBytes(charset);
			} catch (UnsupportedEncodingException var3) {
				throw new RuntimeException("MD5签名过程中出现错误,指定的编码集错误");
			}
		} else {
			return content.getBytes();
		}
	}

	// 获取 InputStream 的 MD5 值
	public static String getInputStreamMD5Str(InputStream inputStream) throws IOException, NoSuchAlgorithmException {
		try (InputStream is = new BufferedInputStream(inputStream)) {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			byte[] buffer = new byte[4096];
			int bytesRead = -1;
			while ((bytesRead = is.read(buffer)) != -1) {
				digest.update(buffer, 0, bytesRead);
			}
			byte[] hash = digest.digest();
			return DatatypeConverter.printHexBinary(hash).toLowerCase();
		}
	}


	//获取文件md5加密后的字符串
	/*public static String getFileMD5Str(File file) throws Exception {
		try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			byte[] buffer = new byte[4096];
			int bytesRead = -1;
			while ((bytesRead = bis.read(buffer)) != -1) {
				digest.update(buffer, 0, bytesRead);
			}
			byte[] hash = digest.digest();
			return DatatypeConverter.printHexBinary(hash).toLowerCase();
		}
	}*/


}